<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/views/QuanXian/quanxianguanli/bumenguanli/bumen/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElTag,ElSwitch } from 'element-plus'
import { Table } from '@/components/Table'
import { getTableListApi, saveTableApi, delTableListApi,getLzrupdDeptStatus,saveTwoTableApi} from '@/api/quanxianapi'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { h, ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { TableColumn } from '@/types/table'
import { FormSchema } from '@/types/form'
import { ElMessage } from 'element-plus'

const { register, tableObject, methods } = useTable<TableData>({
  getListApi: getTableListApi,
  delListApi: delTableListApi,
  response: {
    list: 'list',
    total: 'total'
  },
  defaultParams: {
    title: 's'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

//表格的虚拟数据
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'deptId',
    label: '序号',
    type: 'index',
  },
  {
    field: 'deptName',
    label:'部门名称'
  },
  {
    field: 'deptDescirbe',
    label:'部门描述'
  },
  {
    field: 'createDate',
    label:'创建时间',
    formatter: (row, column, cellValue, index) => {
      let format = 'YYYY-mm-dd HH:MM:SS'
      let date = new Date(cellValue);
      const dataItem = {
        'Y+': date.getFullYear().toString(),
        'm+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
        'H+': date.getHours().toString(),
        'M+': date.getMinutes().toString(),
        'S+': date.getSeconds().toString(),
      };
      Object.keys(dataItem).forEach((item) => {
        const ret = new RegExp(`(${item})`).exec(format);
        if (ret) {
          format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
        }
      });
      return format
    }
  },
  {
    field: 'deptStatus',
    label:'状态',
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  tableObject.currentRow = null
  dialogVisible.value = true
  actionType.value = 'xinzeng'
}

const delLoading = ref(false)

const delData = async (row: TableData | null, multiple: boolean) => {
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? selections.map((v) => v.deptId) : tableObject.currentRow?.deptId,
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const actionType = ref('')

const action = (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  if (row != null){
    row.createDate = null
    row.updateDate = null
    actionType.value = type
    tableObject.currentRow = row
    dialogVisible.value = true
  }
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as TableData
      const res = await saveTableApi(data)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        ElMessage({
          message: '添加成功！',
          type: 'success',
        })
        getList()
      }
    }
  })
}

const savetwo = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as TableData
      const res = await saveTwoTableApi(data)
              .catch(() => {})
              .finally(() => {
                loading.value = false
              })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        ElMessage({
          message: '修改成功！',
          type: 'success',
        })
        getList()
      }
    }
  })
}

allSchemas.searchSchema = reactive<FormSchema[]>([
  {
    field: 'deptName',
    label: '部门名称',
    component: 'Input',
  },
  {
    field: 'createDate',
    component: 'DatePicker',
    label: '请选择时间',
    componentProps: {
      type: 'date',
      valueFormat:'YYYY-MM-DD'
    }
  },
  {
    field: 'deptStatus',
    label: '状态',
    component: 'Select',
    componentProps: {
      options: [
        {
          label:'请选择状态',
          value:''
        },
        {
          label:'启用',
          value:1
        },
        {
          label:'停用',
          value:2
        }
      ]
    }
  }
])

const change = async(row) => {
  const res = await getLzrupdDeptStatus(row).catch(() => {
  })
  if (res) {
    ElMessage({
      message: '修改状态成功！',
      type: 'success',
    })
  }
}

</script>

<template>
  <ContentWrap>
    <div style="width: 2000px">
      <Search
              :model="{ title: '' }"
              :schema="allSchemas.searchSchema"
              @search="setSearchParams"
              @reset="setSearchParams"
      />
    </div>
  </ContentWrap>
  <ContentWrap>

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" v-hasPermi="['example:dialog:edit']" @click="action(row, 'edit')">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="danger" v-hasPermi="['example:dialog:delete']" @click="delData(row, false)">
          {{ t('exampleDemo.del') }}
        </ElButton>

      </template>
      <template #deptStatus="{row}">
        <ElSwitch
                v-model="row.deptStatus"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="启用"
                inactive-text="停用"
                :active-value="1"
                :inactive-value="2"
                @change="change(row)"
        />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType === 'xinzeng'" type="primary" :loading="loading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType === 'edit'" type="primary" :loading="loading" @click="savetwo">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
